#include "utils.h"
#include<sys/epoll.h>
const char *ipstr="127.0.0.1";
const short portid = 8888; 
const int ESIZE = 1024;
int main(){
    /*
    const int SIZE =1024;
    epfd = epoll_create(SIZE);
    创建epoll 树的句柄
    epoll_ctl(epfd,EPOLL_CTL_ADD|EPOLL_CTL_DEL,fd,(struct epoll_event *)ev);
    epoll_wait(epfd,events[SIZE],int timeout);
    */
   int lfd=SOCK_CREATE(SOCK_STREAM,0);
   SOCK_REUSE(lfd);
   SOCK_BIND(lfd,ipstr,portid);
   SOCK_LISTEN(lfd,256);
   struct epoll_event ev;
   struct epoll_event events[ESIZE];
   int epfd = epoll_create(ESIZE);
   if (epfd<0) {
    perror("epoll create failed");
    return -1;
   }
   ev.data.fd = lfd;
   ev.events =EPOLLIN;
   epoll_ctl(epfd,EPOLL_CTL_ADD,lfd,&ev);
   int nready=0;
   char buf[256];
   while (1)
   {
    /* code */
    nready = epoll_wait(epfd,events,ESIZE,-1);
    if(nready<0){
        perror("epoll wait error");
        if(errno==EINTR) {
            continue;
        }
        return -1;
    }else{
        

        for(int i=0;i<nready;++i){
            int sockfd = events[i].data.fd;
            if(sockfd==lfd){
                int cfd = SOCK_ACCEPT(lfd,NULL,NULL);
                ev.data.fd = cfd;
                ev.events = EPOLLIN|EPOLLET;
                epoll_ctl(epfd,EPOLL_CTL_ADD,cfd,&ev);
				//将cfd设置为非阻塞模式
				int flags = fcntl(cfd, F_GETFL, 0);
				flags |= O_NONBLOCK;
				fcntl(cfd, F_SETFL, flags);
                continue;
            }
        while(1){
            memset(buf,0x00,sizeof(buf));
            ssize_t n = read(sockfd,buf,10);
            				if(n==-1)//缓冲区中的数据已经读完了
				if(n==-1){
					if(errno==EAGAIN)
					{
						printf("read over\n");
						break;
					}
					else
					{
						printf("read error\n");
						close(sockfd);
						//将sockfd对应的事件下树
						epoll_ctl(epfd, EPOLL_CTL_DEL, sockfd, NULL);
						break;
					}
				}
            if(n==0){
                close(sockfd);
                epoll_ctl(epfd,EPOLL_CTL_DEL,sockfd,NULL);
                break;
            }else if(n>0) {
                printf("%s\n",buf);
                write(sockfd,buf,n);
            }
        }


        }
    }


   }
   close(epfd);
   close(lfd);
   



}